#include "testbd.h"

TestBD::TestBD():
    QObject()
{
    _count = 0;
    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
}

void TestBD::addTest(const QString &name, quint16 numVis)
{
    QStringList node;
    QString fileName = newFileName();

    node.append(name);
    node.append(fileName);
    node.append(QString().setNum(numVis));
    data.append(node);

    _count = data.count();
}

void TestBD::setData(QList<QStringList> data)
{
    this->data = data;
}

void TestBD::delTest(const QString &name)
{
    int id = -1;

    for(quint32 i = 0; i < _count; i++)
    {
        if(data.at(i).at(0) == name)
        {
            id = i;
            break;
        }
    }
    if(id != -1)
    {
        data.removeAt(id);
        _count--;
    }
}

QString TestBD::getTestFileByName(const QString &name) const
{
    int id = -1;

    for(quint32 i = 0; i < _count; i++)
    {
        if(data.at(i).at(0) == name)
        {
            id = i;
            break;
        }
    }

    if(id == -1)
        return "";

    return data.at(id).at(1);
}

quint32 TestBD::count() const
{
    return _count;
}

void TestBD::setCount(quint32 c)
{
    _count = c;
}

QList<QStringList> TestBD::getData() const
{
    return this->data;
}

QString TestBD::newFileName() const
{
    QString fileName = "ts";
    for(int i = 0; i < FILE_NAME_SIZE; i++)
    {
        fileName += QString().setNum(qrand() % 10);
    }
    fileName += ".tst";
    return fileName;
}

QDataStream &operator <<(QDataStream &out, const TestBD &testdb)
{
    out << quint32(testdb.count()) << testdb.getData();
    return out;
}

QDataStream &operator >>(QDataStream &in, TestBD &testdb)
{
    quint32 count;
    QList<QStringList> data;

    in >> count >> data;
    testdb.setCount(count);
    testdb.setData(data);
    return in;
}
